package cn.zld.sh.sh.ui.renwu;

import android.app.AlertDialog;
import android.app.Dialog;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.squareup.okhttp.Headers;
import com.squareup.okhttp.Response;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.zld.sh.sh.R;
import cn.zld.sh.sh.base.BaseFragment;
import cn.zld.sh.sh.ui.userfragment.UserFragment;
import cn.zld.sh.sh.util.LogUtils;
import cn.zld.sh.sh.util.OkHttpClientManager;
import cn.zld.sh.sh.util.SharedUtils;
import cn.zld.sh.sh.util.ToastUtils;

public class RenwuFragment extends BaseFragment {

    private RenwuViewModel mViewModel;
    private String qdmCookie;
    private boolean logined = false;
    private String user_name;
    private String pass_word;
    private String QDM_PHPSESSID_COOKIE = " QDM_PHPSESSID_COOKIE";                //求大麦cookie名称
    private String QDM_ACCOUNT_COOKIE = " QDM_ACCOUNT_COOKIE";                //求大麦登陆账号
    private String QDM_PASS_COOKIE = " QDM_PASS_COOKIE";                //求大麦登陆账号
    private String QDM_TAOBAO_COOKIE = " QDM_TAOBAO_COOKIE";                //求大麦淘宝账号账号
    private String QDM_DIANFU_START = " QDM_DIANFU_START";                //求大麦垫付最小值
    private String QDM_DIANFU_END = " QDM_DIANFU_END";                //求大麦垫付最大值
    private String QDM_YUANBAO = " QDM_YUANBAO";                //求大麦垫付最大值
    private boolean run = true;
    private boolean showLogin = true;
    private String order2Toekn;
    private String order1Toekn;
    private boolean qiang = false;      //抢单开关
    private String buyerBind;
    private String resultText = "";
    private boolean startLogin = false;
    private int defaultBindIdIndex = 0;
    private boolean isCanncel = false;//垫付或佣金 决定是否退单
    private boolean isSetDianfu = false;//是否已设置垫付
    private String df_start;
    private String df_end;
    private String yuanbao;
    private String platform = "100";


    private Button startBtn;
    private EditText vwUsername;
    private EditText vwPassword;
    private Spinner spinner;
    private TextView showViewFirst;
    private LinearLayout layLogin;
    private LinearLayout laySetting;
    private TextView ydm_account;
    private TextView showView;
    private Button back_to_login;
    private Button start_qiang;
    private Button start_test_voice;
    private Button stop_test_voice;
    private EditText ETdf_start;
    private EditText ETdf_end;
    private EditText ETyuanbao;

    private List midsss;

    public static RenwuFragment newInstance() {
        return new RenwuFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.renwu_fragment, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // TODO: Use the ViewModel

        initView();
        initData();

    }

    private void initView() {
        mViewModel = ViewModelProviders.of(this).get(RenwuViewModel.class);
        vwUsername = (EditText) getActivity().findViewById(R.id.qdm_user_name);
        vwPassword = (EditText) getActivity().findViewById(R.id.qdm_pass_word);
        ydm_account = (TextView) getActivity().findViewById(R.id.ydm_account);
        showView = (TextView) getActivity().findViewById(R.id.showView);
        showViewFirst = (TextView) getActivity().findViewById(R.id.showViewFirst);
        spinner = (Spinner) getActivity().findViewById(R.id.spinner);
        layLogin = (LinearLayout) getActivity().findViewById(R.id.qdm_login_layout);
        laySetting = (LinearLayout) getActivity().findViewById(R.id.qdm_setting);
        ETdf_start = (EditText) getActivity().findViewById(R.id.df_start);
        ETdf_end = (EditText) getActivity().findViewById(R.id.df_end);
        ETyuanbao = (EditText) getActivity().findViewById(R.id.yuanbao);

        start_test_voice = (Button) getActivity().findViewById(R.id.start_test_voice);
        start_test_voice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playvoid(R.raw.qdm);

            }
        });


        stop_test_voice = (Button) getActivity().findViewById(R.id.stop_test_voice);
        stop_test_voice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                destroy();
            }
        });

        back_to_login = (Button) getActivity().findViewById(R.id.back_to_login);
        back_to_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                run = true;
                showLogin = true;
                startLogin = false;
                handler.post(task);

            }
        });

        start_qiang = (Button) getActivity().findViewById(R.id.start_qiang);
        start_qiang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (qiang) {
                    ShowTextTask("停止任务");
                    qiang = false;
                    start_qiang.setText("开始任务");
                    destroy();
                } else {
                    qiang = true;

                    ShowTextTask("开始任务");
                    start_qiang.setText("停止任务");

//                    initDianfu();
                    getMid.start();
                }
            }
        });

        startBtn = (Button) getActivity().findViewById(R.id.rewnStart);
        startBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                user_name = vwUsername.getText().toString();
                pass_word = vwPassword.getText().toString();

                if (user_name.isEmpty() || user_name == null) {
                    ToastUtils.showLongToast(myContext, "用户名不能为空");
                    return;
                }

                if (pass_word.isEmpty() || pass_word == null) {
                    ToastUtils.showLongToast(myContext, "密码不能为空");
                    return;
                }

                InputMethodManager imm = (InputMethodManager) myContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(start_qiang.getWindowToken(), 0);
//                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

                if (!startLogin) {
                    startBtn.setText("登陆中。。。");
                    startLogin = true;
                    getCookie();
                }
            }
        });


    }

    private void initSpinner() {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(myContext, android.R.layout.simple_spinner_item, midsss);
        // 为适配器设置下拉列表下拉时的菜单样式，有好几种样式，请根据喜好选择
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // 将适配器添加到下拉列表上
        spinner.setAdapter(adapter);
        adapter.notifyDataSetChanged();       //通知spinner刷新数据
        spinner.setSelection(defaultBindIdIndex);
        // 为下拉框设置事件的响应

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            /**
             *
             * @param adapterView
             * @param view   显示的布局
             * @param i      在布局显示的位置id
             * @param l      将要显示的数据
             */
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                defaultBindIdIndex = i;
                String[] curMid = midsss.get(defaultBindIdIndex).toString().split("\\|");
                buyerBind = curMid[1];
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    private void initData() {
        user_name = SharedUtils.getString(QDM_ACCOUNT_COOKIE);
        pass_word = SharedUtils.getString(QDM_PASS_COOKIE);
        qdmCookie = SharedUtils.getString(QDM_PHPSESSID_COOKIE);
        String midStrs = SharedUtils.getString(QDM_TAOBAO_COOKIE);

        if (midStrs != null && !midStrs.isEmpty()) {
            midsss = Arrays.asList(midStrs.split("@@@"));
            gtMids.setMids();
        }

        if (user_name != null && !user_name.isEmpty()) {
            vwUsername.setText(user_name);
        }
        if (pass_word != null && !pass_word.isEmpty()) {
            vwPassword.setText(pass_word);
        }

        initDianfu();
    }

    private void initDianfu() {
        //初始化垫付信息

//        String start = ETdf_start.getText().toString();
//        String end = ETdf_end.getText().toString();
//
//        if(!start.isEmpty() && ! end.isEmpty()){
//            df_start = Integer.parseInt(start) + "";
//            df_end = Integer.parseInt(end) + "";
//            isCanncel = true;
//            return;
//        }

        df_start = SharedUtils.getString(QDM_DIANFU_START);
        df_end = SharedUtils.getString(QDM_DIANFU_END);
        yuanbao = SharedUtils.getString(QDM_YUANBAO);
        if (df_start != null && !df_start.isEmpty()) {
            ETdf_start.setText(df_start);
        }
        if (df_end != null && !df_end.isEmpty()) {
            ETdf_end.setText(df_end);
        }
        if (yuanbao != null && !yuanbao.isEmpty()) {
            ETyuanbao.setText(yuanbao);
        }
//        if(df){
//            setDianfu(dfStart, dfEnd);
//        }
    }

    //监听 mids获取情况，如果已获取到了，就调用setMids方法
    private GtMids gtMids = new GtMids() {
        @Override
        public void setMids() {
            if (midsss.size() > 0) {
//                initSpinner();

                SharedUtils.putString(QDM_ACCOUNT_COOKIE, user_name);
                SharedUtils.putString(QDM_PASS_COOKIE, pass_word);
                String midStrs = null;
                for (Object mid : midsss) {
                    if (midStrs == null) {
                        midStrs = mid.toString();
                    } else {
                        midStrs += "@@@" + mid.toString();
                    }
                }
                SharedUtils.putString(QDM_TAOBAO_COOKIE, midStrs);

                String[] curMid = midsss.get(defaultBindIdIndex).toString().split("\\|");
                buyerBind = curMid[1];


                run = true;
                showLogin = false;
                handler.postDelayed(task, 1000);
            }
        }
    };

    private final Runnable task = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            ydm_account.setText(user_name);
            if (run) {
                run = false;
                if (showLogin) {
                    layLogin.setVisibility(View.VISIBLE);
                    laySetting.setVisibility(View.INVISIBLE);
                } else {
                    layLogin.setVisibility(View.INVISIBLE);
                    laySetting.setVisibility(View.VISIBLE);
                    initSpinner();
                }
                handler.post(this);
            }
        }
    };

    private void ShowTextTask(String Text) {
        resultText = Text;
        handler.post(showTextTask);
    }

    private final Runnable showTextTask = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            if (!qiang) return;
            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
            Date curDate = new Date(System.currentTimeMillis());


            showView.setText("\n\n" + showView.getText().toString());
            showView.setText(showViewFirst.getText() + showView.getText().toString());
            showViewFirst.setText(formatter.format(curDate) + "----->" + resultText);

            resultText = "";
        }
    };

    private final Runnable cgStartBtn = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            startBtn.setText("登陆");
            startLogin = false;
        }
    };

    private Runnable vipTask = new Runnable() {
        @Override
        public void run() {

            AlertDialog.Builder builder = new AlertDialog.Builder(myContext);
            // 设置参数
            builder.setTitle("VIP已过期")
                    .setMessage("您的VIP已过期，请续费！")
                    .setPositiveButton("好的", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            handler.post(cgStartBtn);
                        }
                    });
            builder.create().show();
        }
    };

    private void setDianfu(final String start, final String end) {
        if(isSetDianfu) return;
        new Thread() {
            public void run() {
                try {
                    Map<String, String> header = new HashMap<>();
                    header.put("Accept", "*/*");
//                        header.put("Accept-Encoding","gzip, deflate, br");
                    header.put("Accept-Language", "zh-CN,zh;q=0.8");
                    header.put("Connection", "keep-alive");
                    header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                    header.put("Host", "ufo.chongdamai.com");
                    header.put("Origin", "https://ufo.chongdamai.com");
                    header.put("Referer", "https://ufo.chongdamai.com/index/pricesetting.html?platform=" + platform);
                    header.put("X-Requested-With", "XMLHttpRequest");
                    header.put("Upgrade-Insecure-Requests", "1");
                    header.put("User-Agent", userAgent);
                    header.put("Cookie", qdmCookie);

                    OkHttpClientManager.Param[] params = new OkHttpClientManager.Param[]{
                            new OkHttpClientManager.Param("platform", platform),
                            new OkHttpClientManager.Param("taskType", "0"),
                            new OkHttpClientManager.Param("start", start),
                            new OkHttpClientManager.Param("end", end),
                    };

                    Response response = OkHttpClientManager.post("https://ufo.chongdamai.com/index/pricesetting.html", header, params);

                    String html = response.body().string();

                    JSONObject jo = new JSONObject(html);

                    if (jo.getInt("err") == 1) {
//                        Toaster("垫付金额设置成功！");
                        LogUtils.d("垫付金额设置成功");
                        isSetDianfu = true;
                    } else {
                        Toaster("垫付金额设置失败！" + jo.getString("msg"));
                    }

                } catch (Exception e) {
                    Toaster("垫付金额设置异常！");
                }
            }
        }.start();
    }

    //通过网络通信获取 mids
    private GetMid getMid = new GetMid() {

        List mids = new ArrayList();

        @Override
        public void start() {

//            new UserFragment().getUinfo(false);

            if (SharedUtils.getInt("vipStatus") <= 0) {
                qiang = false;
                handler.post(vipTask);
                return;
            }
            getIndexToekn();
        }

        @Override
        public void getIndexToekn() {
            new Thread() {
                public void run() {
                    try {
                        Map<String, String> header = new HashMap<>();
                        header.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
//                        header.put("Accept-Encoding","gzip, deflate, sdch, br");
                        header.put("Accept-Language", "zh-CN,zh;q=0.8");
                        header.put("Connection", "keep-alive");
                        header.put("Host", "ufo.chongdamai.com");
                        header.put("Upgrade-Insecure-Requests", "1");
                        header.put("User-Agent", userAgent);
                        header.put("Cookie", qdmCookie);
                        String platUrl;
//                        initDianfu();
//                        if(isCanncel == 1){
//                            setDianfu(df_start, df_end);
//                            Response response = OkHttpClientManager.getAsyn("https://ufo.chongdamai.com/index/pricesetting.html?platform=" + platform, header);
//                            String html = response.body().string();
//
//                            String[] str1 = html.split("__token__\" value=\"");
//                            str1 = str1[1].split("\"");
//                            order1Toekn = str1[0];
//                            platUrl = "https://ufo.chongdamai.com/index/OrderOne/platform/" + platform + "/__token__/" + order1Toekn;
//
//                        }else{

                        Response response = OkHttpClientManager.getAsyn("https://ufo.chongdamai.com/index/index.html", header);

//                        byte[] b = response.body().bytes(); //获取数据的bytes
//                        String info = new String(b, "gb2312"); //然后将其转为gb2312

                        String html = response.body().string();
//                        html = OkHttpClientManager.unCompress(html);
//                            Log.i("html_log", html);
                        String[] strs1 = html.split("var token = \"");
                        String[] strs2 = strs1[1].split("\"");
                        order1Toekn = strs2[0];
                        platUrl = "https://ufo.chongdamai.com/index/OrderOne/platform/" + platform + "/__token__/" + order1Toekn;
//                        }


                        gMid(platUrl);

                    } catch (Exception e) {
                        ShowTextTask("Err- i tk！");
                        return;
                    }
                }
            }.start();
        }

        private void gMid(final String platUrl) {
            new Thread() {
                public void run() {
                    try {
                        Map<String, String> header = new HashMap<>();
                        header.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
//                        header.put("Accept-Encoding","gzip, deflate, sdch, br");
                        header.put("Accept-Language", "zh-CN,zh;q=0.8");
                        header.put("Cache-Control", "max-age=0");
                        header.put("Connection", "keep-alive");
                        header.put("Host", "ufo.chongdamai.com");
                        header.put("Upgrade-Insecure-Requests", "1");
                        header.put("User-Agent", userAgent);
                        header.put("Cookie", qdmCookie);
                        Response response = OkHttpClientManager.getAsyn(platUrl, header);

                        String html = response.body().string();

                        orderTwoToken(html);
//                        if (!qiang) {
                            splidMId(html);
//                        }

                        return;
                    } catch (Exception e) {
                        ShowTextTask("Err- plu！");
                        return;
                    }
                }
            }.start();
        }

        private void orderTwoToken(String html) {
            String[] token = html.split("__token__\" value=\"");
            token = token[1].split("\"");
            order2Toekn = token[0];
//            genthuan(",垫付：96", ",佣金：186", "NTg1NDc3MDc2NDUy" , "2917158");
            startOrder();
        }

        private void startOrder() {
            if (qiang) {
                InputMethodManager imm = (InputMethodManager) myContext.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(start_qiang.getWindowToken(), 0);
                df_start = ETdf_start.getText().toString();
                df_end = ETdf_end.getText().toString();
                yuanbao = ETyuanbao.getText().toString();

                if (!df_start.isEmpty() && !df_end.isEmpty()) {
                    df_start = Integer.parseInt(df_start) + "";
                    df_end = Integer.parseInt(df_end) + "";
                    SharedUtils.putString(QDM_DIANFU_START, df_start);
                    SharedUtils.putString(QDM_DIANFU_END, df_end);
                    setDianfu(df_start, df_end);
                }

                if (!yuanbao.isEmpty() && !yuanbao.isEmpty()) {
                    yuanbao = Float.parseFloat(yuanbao) + "";
                    SharedUtils.putString(QDM_YUANBAO, yuanbao);
                }
                new Thread() {
                    public void run() {
                        try {
                            Map<String, String> header = new HashMap<>();
                            header.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
//                            header.put("Accept-Encoding","gzip, deflate, br");
                            header.put("Accept-Language", "zh-CN,zh;q=0.8");
                            header.put("Cache-Control", "max-age=0");
                            header.put("Connection", "keep-alive");
//                            header.put("Content-Length","59");
                            header.put("Content-Type", "application/x-www-form-urlencoded");
                            header.put("Host", "ufo.chongdamai.com");
                            header.put("X-Requested-With", "XMLHttpRequest");
                            header.put("Origin", "https://ufo.chongdamai.com");
//                            header.put("Referer","https://ufo.chongdamai.com/index/OrderOne/platform/" + platform + "/__token__/728c44b8a494b4c36bb06f365d194f75");
                            header.put("Upgrade-Insecure-Requests", "1");
                            header.put("User-Agent", userAgent);
                            header.put("Cookie", qdmCookie);
                            OkHttpClientManager.Param[] params = new OkHttpClientManager.Param[]{
                                    new OkHttpClientManager.Param("paltform", platform),
                                    new OkHttpClientManager.Param("taskType", "0"),
                                    new OkHttpClientManager.Param("buyerBind", buyerBind),
                            };
                            Response response = OkHttpClientManager.post("https://ufo.chongdamai.com/index/orderone.html", header, params);

                            String html = response.body().string();

                            JSONObject jo = new JSONObject(html);
                            if (jo.getInt("err") == 1) {
                                // ok
                                startOrder2();
                            } else {
//                                ToastUtils.showLongToast(getActivity(), jo.getString("msg"));
                                ShowTextTask(jo.getString("msg"));

                            }

                            return;
                        } catch (Exception e) {
                            ShowTextTask("Err- odo！");
                            return;
                        }
                    }
                }.start();
            }
        }

        private void startOrder2() {
            if (qiang) {
                new Thread() {
                    public void run() {
                        try {
                            Map<String, String> header = new HashMap<>();
                            header.put("Accept", "*/*");
//                            header.put("Accept-Encoding","gzip, deflate, br");
                            header.put("Accept-Language", "zh-CN,zh;q=0.8");
                            header.put("Connection", "keep-alive");
//                            header.put("Content-Length","40");
                            header.put("Content-Type", "application/x-www-form-urlencoded");
                            header.put("Host", "ufo.chongdamai.com");
                            header.put("Origin", "https//ufo.chongdamai.com");
                            header.put("X-Requested-With", "XMLHttpRequest");
//                            header.put("Referer","https//ufo.chongdamai.com/index/OrderOne/platform/" + platform + "/__token__/" + order1Toekn);
                            header.put("User-Agent", userAgent);
                            header.put("Cookie", qdmCookie);
                            OkHttpClientManager.Param[] params = new OkHttpClientManager.Param[]{
                                    new OkHttpClientManager.Param("__token__", order2Toekn),
                                    new OkHttpClientManager.Param("buyerBind", buyerBind)
                            };
                            Response response = OkHttpClientManager.post("https://ufo.chongdamai.com/index/ordertwo.html", header, params);

//                            String html = response.body().string();

//                            JSONObject jo = new JSONObject(html);
                            if (response.code() == 200) {
                                // ok
                                getOrderResult(0);
                            } else {
//                                ToastUtils.showLongToast(getActivity(), "获取派单错误！");
                                ShowTextTask("获取派单错误！");

                            }

                            return;
                        } catch (Exception e) {
                            ShowTextTask("Err- odt！");
                            return;
                        }
                    }
                }.start();
            }
        }

        private void getOrderResult(int cnt) {

            cnt += 1;
            final int cnts = cnt;
            if (qiang) {
                new Thread() {
                    public void run() {
                        try {
                            LogUtils.i("orderresult");
                            Thread.sleep(1000);
                            ShowTextTask("没有拍到单");
                            Thread.sleep(1000);
//                            if(cnts < 5){
//                                getOrderResult(cnts);
//                                return;
//                            }
//                            Thread.sleep(1000);
                            Map<String, String> header = new HashMap<>();
                            header.put("Accept", "*/*");
//                            header.put("Accept-Encoding","gzip, deflate, br");
                            header.put("Accept-Language", "zh-CN,zh;q=0.8");
                            header.put("Connection", "keep-alive");
//                            header.put("Content-Length","16");
                            header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                            header.put("Host", "ufo.chongdamai.com");
                            header.put("X-Requested-With", "XMLHttpRequest");
                            header.put("Origin", "https://ufo.chongdamai.com");
                            header.put("Referer", "https://ufo.chongdamai.com/index/ordertwo.html");
                            header.put("User-Agent", userAgent);
                            header.put("Cookie", qdmCookie);
                            OkHttpClientManager.Param[] params = new OkHttpClientManager.Param[]{
                                    new OkHttpClientManager.Param("buyerBind", buyerBind)
                            };
                            Response response = OkHttpClientManager.post("https://ufo.chongdamai.com/index/dispatchorder.html", header, params);

//                            {"err":0,"msg":"没有拍到单"}
                            String html = response.body().string();

                            JSONObject jo = new JSONObject(html);

                            //{"err":0,"msg":"没有拍到单"}

                            if (jo.getInt("err") == 0 && jo.getString("msg").equals("没有拍到单")) {
                                ShowTextTask(jo.getString("msg"));
                                // ok
//                                startOrder2();
                                if (cnts <= 8) {
                                    getOrderResult(cnts);
                                } else {
                                    getMid.start();
                                }
                            } else if (jo.getInt("err") == 1) {
//                                ToastUtils.showLongToast(getActivity(), jo.getString("msg"));
                                String[] products = jo.getString("msg").split("sou_name\">");
                                String[] pros = products[1].split("<");
                                String productName = pros[0];
                                products = products[1].split("red\">");
                                String[] prices = products[1].split("<");
                                String yongjin = ",佣金：" + prices[0];
                                prices = products[2].split("<");
                                String price = ",垫付：" + prices[0];

                                prices = products[2].split("this,");
                                prices = prices[1].split(",");
                                String orderId = prices[0];

                                prices = products[2].split("data-id=\"");
                                prices = prices[1].split("\"");
                                String productId = prices[0];

//                                resultText = "(" + orderId + ")产品：" + productName + yongjin + price;
                                ShowTextTask("(" + orderId + ")产品：" + productName + yongjin + price);
                                genthuan(price, yongjin, productId, orderId);
//                                ling(orderId);

                            }

                            return;
                        } catch (Exception e) {
                            ShowTextTask("Err---获取接单信息错误！");
                            getMid.start();
                            return;
                        }
                    }
                }.start();
            }
        }

        private void genthuan(String price, String yongjin, final String proId, String orderId) {

            if (!qiang) return;
            df_start = ETdf_start.getText().toString();
            df_end = ETdf_end.getText().toString();
            yuanbao = ETyuanbao.getText().toString();

            //佣金合适就领取
            if (!yuanbao.isEmpty()) {
                yuanbao = Float.parseFloat(yuanbao) + "";
                yongjin = yongjin.replace(",佣金：", "");
                //如果垫付金额任意一个没有设置，并且
                if (Float.parseFloat(yongjin) >= Float.parseFloat(yuanbao)) {
                    isCanncel = false;                                                              //佣金符合，不退单
                }else{
                    isCanncel = true;                                                               //佣金少于设置的元宝数，退单
                }
            }else{
                isCanncel = false;                                                                  //佣金不限，不退单
            }

            //垫付合适就领取
            if(!isCanncel){
                if (!df_start.isEmpty() && !df_end.isEmpty()) {
                    df_start = Integer.parseInt(df_start) + "";
                    df_end = Integer.parseInt(df_end) + "";
                    price = price.replace(",垫付：", "");
                    if (Integer.parseInt(price) >= Integer.parseInt(df_start) && Integer.parseInt(price) <= Integer.parseInt(df_end)) {
                        isCanncel = false;                                                              //垫付 >= 最小垫付 <= 最大垫付，不退单
                    }else{
                        isCanncel = true;                                                               //垫付 < 最小垫付 或> 最大垫付，退单
                    }
                }else{
                    isCanncel = false;                                                                  //垫付不限，不退单
                }
            }

            if(!isCanncel){
                ling(orderId);
                return;
            }





            new Thread() {
                public void run() {
                    try {
                        Map<String, String> header = new HashMap<>();
                        header.put("Accept", "*/*");
//                            header.put("Accept-Encoding","gzip, deflate, br");
                        header.put("Accept-Language", "zh-CN,zh;q=0.8");
                        header.put("Connection", "keep-alive");
//                            header.put("Content-Length","16");
                        header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                        header.put("Host", "ufo.chongdamai.com");
                        header.put("X-Requested-With", "XMLHttpRequest");
                        header.put("Origin", "https://ufo.chongdamai.com");
                        header.put("Referer", "https://ufo.chongdamai.com/index/ordertwo.html");
                        header.put("User-Agent", userAgent);
                        header.put("Cookie", qdmCookie);
                        OkHttpClientManager.Param[] params = new OkHttpClientManager.Param[]{
                                new OkHttpClientManager.Param("goods", proId),
                        };
                        Response response = OkHttpClientManager.post("https://ufo.chongdamai.com/index/replacementtask.html", header, params);

                        String html = response.body().string();
//                            String html = "{\"code\":\"00000\",\"href\":\"https:\\/\\/ufo.chongdamai.com\\/order_tb_normal\\/setone.html?order_id=13566520\"}";

                        JSONObject jo = new JSONObject(html);
                        //{"err":100006,"msg":"请完成未完成的任务","code":1}
                        if (jo.getInt("err") == 1) {
                            ShowTextTask("订单不符合要求，已更换！");
                        } else {
                            ShowTextTask(jo.getString("msg"));
                        }
                        getMid.start();
                    } catch (Exception e) {
                        getMid.start();
                        return;
                    }
                }
            }.start();
        }

        private void ling(final String orderId) {

            if (qiang) {
                new Thread() {
                    public void run() {
                        try {
                            String postUrl = "https://ufo.chongdamai.com/order/createorder.html";
                            LogUtils.i("orderresult");
                            Map<String, String> header = new HashMap<>();
                            header.put("Accept", "*/*");
//                            header.put("Accept-Encoding","gzip, deflate, br");
                            header.put("Accept-Language", "zh-CN,zh;q=0.8");
                            header.put("Connection", "keep-alive");
//                            header.put("Content-Length","16");
                            header.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                            header.put("Host", "ufo.chongdamai.com");
                            header.put("X-Requested-With", "XMLHttpRequest");
                            header.put("Origin", "https://ufo.chongdamai.com");
                            header.put("Referer", "https://ufo.chongdamai.com/index/ordertwo.html");
                            header.put("User-Agent", userAgent);
                            header.put("Cookie", qdmCookie);
                            OkHttpClientManager.Param[] params = new OkHttpClientManager.Param[]{
                                    new OkHttpClientManager.Param("id", orderId),
                                    new OkHttpClientManager.Param("bid", buyerBind)
                            };
                            Response response = OkHttpClientManager.post(postUrl, header, params);

                            String html = response.body().string();

//                            String html = "{\"code\":\"00000\",\"href\":\"https:\\/\\/ufo.chongdamai.com\\/order_tb_normal\\/setone.html?order_id=13566520\"}";

                            JSONObject jo = new JSONObject(html);
                            //{"err":100006,"msg":"请完成未完成的任务","code":1}

                            if (jo.getString("code").equals("1")) {
                                if (jo.getString("err").equals("100006")) {
                                    playvoid(R.raw.qdm);
                                    ShowTextTask(jo.getString("msg"));
                                    handler.post(cgStartBtn);
                                } else if (jo.getString("err").equals("1008")) {
                                    //{"err":1008,"msg":"该任务被抢走，呜呜！！","code":1}
                                    ShowTextTask(jo.getString("msg"));
                                    getMid.start();
                                }
                            } else if (jo.getString("code").equals("00000")) {
                                //{"code":"00000","href":"https:\/\/ufo.chongdamai.com\/order_tb_normal\/setone.html?order_id=13566520"}
                                playvoid(R.raw.qdm);
                                ShowTextTask("接到任务了！");

                            } else {
                                playvoid(R.raw.qdm);
                            }
                        } catch (Exception e) {
                            ShowTextTask("Err- ling 获取接单信息错误！");
                            getMid.start();
                            return;
                        }
                    }
                }.start();
            }
        }

        /**
         * 获取mid（绑定淘宝的id）
         * @param html
         */
        private void splidMId(String html) {
            String[] mid1s = {};
            String[] mid2s = {};

            if (html.indexOf("float: left; position: absolute; top: 30%; left: 43%; color: #999;") < 0) {
                handler.post(cgStartBtn);
                Toaster("请登陆平台添加淘宝、京东、拼多多账户！");
                return;
            }

            String[] strs1 = html.split("float: left; position: absolute; top: 30%; left: 43%; color: #999;\">");
            String[] status;
            String accnt = "";
            String[] kejie;

            for(int i = 1; i< strs1.length; i++){
                status = strs1[i].split("<");
                if (status[0].equals("审核通过")) {
                    //账号
                    String[] account = strs1[i-1].split("style=\"display: block;padding-top: 2%;\">");
                    account = account[1].split("<");
                    accnt = account[0];
                    //可接
                    kejie = strs1[i-1].split("今日可接");
                    kejie = kejie[1].split("<span>");
                    kejie = kejie[1].split("</span>");

                    mid1s = strs1[i].split("m-id=\"");
                    mid2s = mid1s[1].split("\"");
                    accnt = accnt + "|" + mid2s[0] + "|" + "可接：" + kejie[0];
                    if (!mids.contains(accnt)) {
                        mids.add(accnt);
                    }
                }
            }

//            status = strs1[1].split("<");
//            if (status[0].equals("审核通过")) {
//                String[] account = strs1[0].split("style=\"display: block;padding-top: 2%;\">");
//                account = account[1].split("<");
//                accnt = account[0];
//                mid1s = strs1[1].split("m-id=\"");
//                mid2s = mid1s[1].split("\"");
//                accnt = accnt + "|" + mid2s[0];
//                if (!mids.contains(accnt)) {
//                    mids.add(accnt);
//                }
//            }
//
//            status = strs1[2].split("<");
//            if (status[0].equals("审核通过")) {
//                String[] account = strs1[1].split("style=\"display: block;padding-top: 2%;\">");
//                account = account[1].split("<");
//                accnt = account[0];
//                mid1s = strs1[2].split("m-id=\"");
//                mid2s = mid1s[1].split("\"");
//                accnt = accnt + "|" + mid2s[0];
//                if (!mids.contains(accnt)) {
//                    mids.add(accnt);
//                }
//            }
            midsss = mids;
            gtMids.setMids();
//            return mids;


        }
    };

    private interface GetMid {
        public void start();

        public void getIndexToekn();
    }

    private interface GtMids {
        public void setMids();
    }


    /**
     * 获取cookie
     */
    private void getCookie() {
//        qdmCookie = SharedUtils.getString( QDM_PHPSESSID_COOKIE);
        if (user_name.equals(SharedUtils.getString(QDM_ACCOUNT_COOKIE))) {
            if (qdmCookie != null && !qdmCookie.isEmpty() && qdmCookie.indexOf(";qlo") > 0) {
                getMid.start();
                return;
            }
        }

        SharedUtils.putString(QDM_ACCOUNT_COOKIE, user_name);
        SharedUtils.putString(QDM_PASS_COOKIE, pass_word);

        new Thread() {
            public void run() {
                try {
                    Map<String, String> headers = new HashMap<String, String>();
                    headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
                    headers.put("Accept-Encoding", "gzip, deflate, sdch, br");
                    headers.put("Accept-Language", "zh-CN,zh;q=0.8");
                    headers.put("Connection", "keep-alive");
                    headers.put("Host", "ufo.chongdamai.com");
                    headers.put("Upgrade-Insecure-Requests", "1");
//                    headers.put("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36");
                    headers.put("User-Agent", userAgent);
                    Response response = OkHttpClientManager.getAsyn("https://ufo.chongdamai.com/login/index.html?ret=http%3A%2F%2Fufo.chongdamai.com%2F", headers);
                    putCookie(response);

                    return;
                } catch (Exception e) {
                    Toaster("Err- ck！");
                    return;
                }
            }
        }.start();
    }

    /**
     * 登陆账号
     */
    private void login() {
        new Thread() {
            public void run() {
                OkHttpClientManager.Param[] params = new OkHttpClientManager.Param[]{
                        new OkHttpClientManager.Param("user_name", user_name),
                        new OkHttpClientManager.Param("pass_word", pass_word)
                };
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Cookie", "PHPSESSID=" + qdmCookie);
                headers.put("Host", "ufo.chongdamai.com");
                headers.put("Connection", "keep-alive");
//                headers.put("Content-Length", "38");
                headers.put("Accept", "*/*");
                headers.put("Origin", "https://ufo.chongdamai.com");
                headers.put("X-Requested-With", "XMLHttpRequest");
                headers.put("User-Agent", userAgent);
                headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                headers.put("Referer", "https://ufo.chongdamai.com/login/index.html?ret=http%3A%2F%2Fufo.chongdamai.com%2F");
                headers.put("Accept-Encoding", "gzip, deflate, br");
                headers.put("Accept-Language", "zh-CN,zh;q=0.9");
                try {
                    Response response = OkHttpClientManager.post("https://ufo.chongdamai.com/login/index.html?ret=http%3A%2F%2Fufo.chongdamai.com%2F", headers, params);

                    //{"code":1,"msg":"登陆成功","data":"","url":"http:\/\/ufo.chongdamai.com\/","wait":3}
                    String result = response.body().string();
                    Log.i("ydm_cookie", result);
                    JSONObject jbo = new JSONObject(result);

//                    ToastUtils.showMessage(jbo.getString("msg"));
                    if (jbo.getInt("code") == 1) {
                        putCookie(response);
                        logined = true;
                        getMid.start();
                    } else {
                        Toaster(jbo.getString("msg"));
                        handler.post(cgStartBtn);
                    }

                } catch (Exception e) {
                    Toaster("Err- dlg！");
                    return;
                }
            }
        }.start();
    }

    /**
     * 保存cookie到本地
     *
     * @param response
     */
    private void putCookie(Response response) {
        Headers headers = response.headers();
        //PHPSESSID=m9n7tavu4212gatcf6n1esa01e; expires=Fri, 05-Apr-2019 15:56:01 GMT; Max-Age=2592000; path=/
        List<String> cookies = headers.values("Set-Cookie");
        if (cookies.size() == 0) {
            if (!qdmCookie.isEmpty()) {
                login();
                return;
            }
            handler.post(cgStartBtn);
            return;
        }
        for (int i = 0; i < cookies.size(); i++) {
            String[] cks = cookies.get(i).split(";");
            for (int j = 0; j < cks.length; j++) {
                String[] coos = cks[j].split("=");
                if (coos[0].equals("PHPSESSID")) {
                    qdmCookie = cks[j].trim() + ";";
                    SharedUtils.putString(QDM_PHPSESSID_COOKIE, qdmCookie);
                    login();
                }
                if (coos[0].equals("qlo")) {
                    qdmCookie += "" + cks[j] + ";";
                    SharedUtils.putString(QDM_PHPSESSID_COOKIE, qdmCookie);

                }
            }
//                        if(cookies[i].)
        }
    }

}
